package com.cn.login.controller;

import com.cn.common.pojo.CommonResult;
import com.cn.common.pojo.LoginParams;
import com.cn.login.code.RandomValidateCode;
import com.cn.login.service.UserServiceS;
import io.swagger.annotations.Api;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Objects;

@Api(tags = "JWT登录")
@RestController
@RequestMapping("JWTuser")
public class JWTUserController {
    @Value("${jwt.tokenHead}")
    String tokenHead;
    @Autowired
    UserServiceS userServiceS;
    @PostMapping("/login")
    public CommonResult<Object> login(@RequestBody LoginParams loginParams, HttpServletRequest request){
        String code = loginParams.getCode();
        String sessionCode = request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY).toString();
        HashMap<String, String> data = new HashMap<>();
        String token=null;
        try {
            token=userServiceS.login(loginParams);
        } catch (Exception exception) {
            exception.printStackTrace();
            return CommonResult.validateFailed("名字密码不要乱输");
        }
        if (StringUtils.isEmpty(token)){
            return CommonResult.validateFailed("名字密码不要乱输");
        }
        if(Objects.equals(code,sessionCode)) {

            HttpSession session = request.getSession();
            session.setAttribute("username", loginParams.getUsername());
            hashCode();
        data.put("tokenHead",tokenHead);
        data.put("access_token",token);}
        else {
            return null ;
        }
        return CommonResult.success(data);}

    public CommonResult test(Authentication authentication){
        return CommonResult.success(authentication);
    }
    /**
     * 远程权限验证
     * @param uri
     * @param username
     * @return
     */
    @RequestMapping("/checkAccessToUri")
    public CommonResult checkAccessToUri( String uri,  String username){
        return userServiceS.checkAccessToUri(uri,username);
    }
}
